#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define ONE     1       // 1 0000 0001
#define TWO     (1<<1)  // 2 0000 0010
#define THREE   (1<<2)  // 4 0000 0100
#define FOUR    (1<<3)  // 8 0000 1000

void print(int flag)
{
    if(flag & ONE)
        printf("one\n");    // 可以替换成其他代码
    if(flag & TWO)
        printf("two\n");
    if(flag & THREE)
        printf("three\n");
    if(flag & FOUR)
        printf("four\n");
}


int main()
{
    // 5
    printf("stdin->fd:  %d\n", stdin->_fileno);
    printf("stdout->fd: %d\n", stdout->_fileno);
    printf("stderr->fd: %d\n", stderr->_fileno);

    FILE *fp1 = fopen("log1.txt", "w");
    if(fp1 == NULL)  return 1;
    printf("fd1: %d\n", fp1->_fileno); 
    FILE *fp2 = fopen("log2.txt", "w");
    if(fp2 == NULL)  return 1;
    printf("fd2: %d\n", fp2->_fileno); 
    FILE *fp3 = fopen("log3.txt", "w");
    if(fp3 == NULL)  return 1;
    printf("fd3: %d\n", fp3->_fileno); 

    // 4
    const char *message = "hello Linux file!\n";
    write(1, message, strlen(message));
    fprintf(stdout, message, 10);
    fflush(stdout);

    //// 3 文件描述符
    //int fda = open("loga.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    //printf("fda: %d\n", fda);
    //int fdb = open("logb.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    //printf("fdb: %d\n", fdb);
    //int fdc = open("logc.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    //printf("fdc: %d\n", fdc);
    //int fdd = open("logd.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    //printf("fdd: %d\n", fdd);
    
    //// 2 标记位传参
    //// | 有一个1就为1 -> 0 | 1 = 1
    //print(ONE);
    //printf("\n");
    //print(TWO);
    //printf("\n");
    //print(ONE | TWO);
    //printf("\n");
    //print(ONE | TWO | THREE);
    //printf("\n");
    //print(FOUR);
    //printf("\n");
    //print(ONE | TWO | FOUR);
    //printf("\n");

    //// 1
    //umask(0);
    //// system call
    //int fd = open("log.txt", O_WRONLY | O_CREAT | O_TRUNC, 0666);
    //if(fd < 0)
    //{
    //    perror("open fail\n");
    //    return 1;
    //}

    ////const char *message = "hello Linux file!\n";
    //const char *message = "haaa\n";
    //write(fd, message, strlen(message));
    //
    //close(fd);

    return 0;
}
